import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:common/l10n/generated/messages_all.dart';
import 'package:common/locale/locale_config.dart';
import 'package:common/locale/multiple_localizations.dart';

class AppLocalizations {
  final String locale;

  AppLocalizations(this.locale);

//  static AppLocalizations current;

  static const AppLocalizationDelegate delegate = AppLocalizationDelegate();

//  static Future<AppLocalizations> load(Locale locale) {
//    final name = (locale.countryCode?.isEmpty ?? false)
//        ? locale.languageCode
//        : locale.toString();
//    final localeName = Intl.canonicalizedLocale(name);
//    return initializeMessages(localeName).then((_) {
//      Intl.defaultLocale = localeName;
//      AppLocalizations.current = AppLocalizations();
//
//      return AppLocalizations.current;
//    });
//  }

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  // ignore: non_constant_identifier_names
  OK() => Intl.message(
        'OK',
        name: 'OK',
        desc: 'OK',
      );

  // ignore: non_constant_identifier_names
  tempAppTitle() => Intl.message(
        'tempAppTitle',
        name: 'tempAppTitle',
        desc: 'tempAppTitle',
      );

  cancel() => Intl.message(
    'cancel',
    name: 'cancel',
    desc: 'cancel',
  );
}

class AppLocalizationDelegate extends LocalizationsDelegate<AppLocalizations> {
  const AppLocalizationDelegate();

  List<Locale> get supportedLocales {
    return AppLocaleConfig.supportedLocales;
  }

  @override
  bool isSupported(Locale locale) => _isSupported(locale);

  @override
  Future<AppLocalizations> load(Locale locale) => MultipleLocalizations.load(
      initializeMessages, locale, (l) => AppLocalizations(l),
      setDefaultLocale: true);

  @override
  bool shouldReload(AppLocalizationDelegate old) => false;

  bool _isSupported(Locale locale) {
    if (locale != null) {
      for (var supportedLocale in supportedLocales) {
        if (supportedLocale.languageCode == locale.languageCode) {
          return true;
        }
      }
    }
    return false;
  }
}
